import { Platform } from "react-native";

type WebErrorEvent = {
  preventDefault: () => void;
  stopImmediatePropagation: () => void;
  reason?: { message?: string } | null;
  error?: { message?: string } | null;
};

export const setupErrorHandler = () => {
  if (Platform.OS === "web" && typeof window !== "undefined") {
    const handleWebError = (message: string): boolean => {
      if (message?.includes("is not available on web")) {
        console.warn(`[Web 兼容性提示] 当前浏览器环境不支持该功能: ${message}`);
        return true;
      }
      return false;
    };

    window.addEventListener(
      "unhandledrejection",
      (event: WebErrorEvent) => {
        if (handleWebError(event.reason?.message || "")) {
          event.preventDefault();
          event.stopImmediatePropagation();
          event.reason = null;
        }
      },
      { capture: true }
    );

    window.addEventListener(
      "error",
      (event: WebErrorEvent) => {
        if (handleWebError(event.error?.message || "")) {
          event.preventDefault();
          event.stopImmediatePropagation();
          event.error = null;
        }
      },
      { capture: true }
    );

    const originalReject = Promise.reject.bind(Promise);
    Promise.reject = function <T = never>(reason: {
      message: string;
    }): Promise<T> {
      if (
        typeof reason === "object" &&
        reason?.message &&
        handleWebError(reason.message)
      ) {
        return Promise.resolve() as Promise<T>;
      }
      return originalReject(reason);
    };
  }
};
